<template>
  <el-form ref="ruleForm" :model="goodsInfo" class="goods-details">
    <headline v-if="titleShow" :headline="'商品详情页'">
      <span slot="head"><el-button type="text" @click="advertisingGuidelines">点击查看《沃尔玛大卖场电商商品详情页标准》</el-button></span>
    </headline>
    <div v-if="resourceDiffFlag.length" class="navleft">
      <div class="links">
        注意:
        <span v-for="item in resourceDiffFlag" :key="item.channalId">
          <span class="links-item" @click="goJump(item.channalId)">{{ item.channalName }}</span>
        </span>
        渠道的图片不一样，点击查看
      </div>
    </div>
    <el-form-item v-if="!isDisabled" prop="skuContentResources" class="form" :rules="{ validator: validator, trigger: 'blur' }">
      <div class="uploadPhoto">
        <draggable v-model="goodsInfo.skuContentResources" draggable=".elImg" animation="300" @end="end">
          <transition-group ref="transitionGroupRef" style="display: block">
            <div v-for="item in goodsInfo.skuContentResources" :key="item.resourceUrl" :edit="item.edit" class="elImg">
              <el-image :src="item.resourceUrl | transImgUrl" :preview-src-list="goodsInfo.skuContentResources | transUrlName" />
              <div v-if="!isDisabled" class="del" @click="imgClick(item.resourceUrl)">
                <i class="el-icon-delete" />
              </div>
            </div>
          </transition-group>
        </draggable>
        <el-upload
          v-if="!isDisabled"
          :auto-upload="false"
          multiple
          :on-change="handleOnChange"
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          accept=".jpg,.jpeg"
        >
          <i class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </div>
      <div class="tip">图片尺寸:宽 750px，仅支持JPG格式，详情页不能整张长图提交，需独立切片，单切片高度1000px，每张切片图不大于1MB</div>
    </el-form-item>
    <div class="picList" v-html="content" />
    <special v-if="isShowSpecial" :is-disabled="isDisabled" :goods-info="goodsInfo" :placeholder="'请输入三品一械注册证编号'" />
  </el-form>
</template>

<script>
import draggable from 'vuedraggable'
import headline from '@/views/coi/components/headline.vue'
import special from './special.vue'
import { uploadSkuContentResource, deleteSkuContentResource } from '@/api/coi/onlineTaskAPI/sku'
import { uploadSkuContentResource2, deleteSkuContentResource2 } from '@/api/coi/onlineTaskAPI/sku'
import eventBus from '@/utils/eventBus'
import { createPicDom } from '@/views/coi/commonJs/createPicDom.js'
import { authentication } from '@/utils/processingData.js'

export default {
  name: 'DetailPage',
  components: { headline, draggable, special },
  filters: {
    transUrlName(imgArr) {
      return imgArr.map((e) => authentication(e.resourceUrl))
    },
    transImgUrl(url) {
      return authentication(url)
    }
  },
  props: {
    goodsInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    titleShow: {
      type: Boolean,
      default: true
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    id: {
      type: [String, Number],
      default: ''
    },
    buildStandard: {
      type: Number,
      default: 0
    },
    fromPage: {
      type: String,
      default: 'making'
    },
    channelId: {
      type: String,
      default: ''
    },
    processId: {
      type: Number,
      default: 0
    },
    resourceDiffFlag: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      num: 0,
      validator: (rule, value, callback) => {
        if (this.fromPage === 'commodityLibrary') {
          if (!this.goodsInfo.skuContentResources || (Array.isArray(this.goodsInfo.skuContentResources) && !this.goodsInfo.skuContentResources.length)) {
            callback(new Error('*商品详情页不能为空'))
          } else callback()
        } else {
          if (this.buildStandard !== 1 && Array.isArray(this.goodsInfo.skuContentResources) && !this.goodsInfo.skuContentResources) {
            callback(new Error('*商品详情页不能为空'))
          } else callback()
        }
      },
      isShowSpecial: true
    }
  },
  computed: {
    content() {
      return createPicDom(this.goodsInfo.skuContentResources, 'resourceUrl', true)
    }
  },
  mounted() {
    if (this.$route.params.type && this.$route.params.type === 'edit') this.isShowSpecial = false
    console.log('*****', this.isShowSpecial)
  },
  methods: {
    imgClick(url) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delImg(url)
        })
        .catch()
    },
    async delImg(url) {
      const skuId = this.id
      let param = {}
      if (this.fromPage === 'commodityLibrary') {
        param = {
          channelId: this.channelId,
          resourceUrl: url,
          processId: this.processId,
          resourceType: 1
        }
      }
      const { result } = this.fromPage === 'commodityLibrary' ? await deleteSkuContentResource2(param) : await deleteSkuContentResource({ url, skuId })
      if (result) {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        if (this.fromPage === 'commodityLibrary') {
          this.goodsInfo.skuContent.content = ''
        }
        const index = this.goodsInfo.skuContentResources.findIndex((item) => item.resourceUrl === url)
        this.goodsInfo.skuContentResources.splice(index, 1)
        this.end()
      }
    },
    createBody(src) {
      return `<div style="padding-bottom: 1px;"><img src="${src}" style="width: 100%;max-width: 750px;" /></div>`
    },
    end() {
      const _this = this
      if (!this.goodsInfo.skuContentResources || (Array.isArray(this.goodsInfo.skuContentResources) && !this.goodsInfo.skuContentResources.length)) return
      const arrsRCDOM = this.goodsInfo.skuContentResources.map((item) => _this.createBody(item.resourceUrl))
      const DomString = arrsRCDOM.join('')
      if (!this.goodsInfo.skuContent) {
        const sku = this.goodsInfo.skuContentResources[this.goodsInfo.skuContentResources.length - 1]
        this.goodsInfo.skuContent = {
          processId: sku.processId,
          channelId: sku.channelId
        }
      }
      this.goodsInfo.skuContent.content = `<div>${DomString}</div>`
      if (this.fromPage === 'commodityLibrary') {
        eventBus.$emit('detailChange', true)
        this.$parent.operationCode[1] = 140
      }
    },
    async handleOnChange(file) {
      try {
        if (file.raw.type !== 'image/jpg' && file.raw.type !== 'image/jpeg') {
          this.showMessage('仅支持上传jpg格式的图片！', 'error')
          return
        }
        const size = file.size / 1024 / 1024
        if (size > 1) {
          this.$message({
            type: 'error',
            message: '图片的大小大于1M'
          })
          return
        }
        this.num++
        eventBus.$emit('loadingChange', true)
        const formData = new FormData()
        formData.append('file', file.raw)
        if (this.fromPage === 'commodityLibrary') {
          formData.append('channelId', this.channelId)
          formData.append('processId', this.processId)
          formData.append('resourceType', 1)
        } else {
          formData.append('skuId', this.id)
        }
        const result = this.fromPage === 'commodityLibrary' ? await uploadSkuContentResource2(formData) : await uploadSkuContentResource(formData)
        if (result.code === '0') {
          if (!Array.isArray(this.goodsInfo.skuContentResources)) this.goodsInfo.skuContentResources = []
          this.goodsInfo.skuContentResources.push(result.result)
          this.$nextTick(() => {
            this.end()
          })
        }
      } finally {
        this.num--
        eventBus.$emit('loadingChange', false)
        // if (this.num === 0) eventBus.$emit('loadingChange', false)
      }
    },
    submitForm() {
      let flag = null
      this.$refs.ruleForm.validate((valid) => {
        flag = valid
      })
      return flag
    },
    advertisingGuidelines() {
      const guideBaseUrl = window.appConfig.operationGuideUrl
      window.open(`${guideBaseUrl}/display/PDF/沃尔玛大卖场商品详情页标准.pdf`)
    },
    goJump(channalId) {
      this.$emit('goJumpDown', channalId)
    }
  }
}
</script>

<style lang="scss" scoped>
.form {
  padding: 0 10px;
}
.navleft {
  margin-left: 30px;
  .links {
    color: #f56c6c;
    .links-item {
      color: red;
      text-decoration: underline;
      font-weight: bold;
      margin: 0 5px;
    }
    .links-item:hover {
      cursor: pointer;
    }
  }
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader /deep/.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.uploadPhoto {
  min-height: 100px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  .elImg {
    height: 100px;
    width: 100px;
    display: inline-block;
    margin-right: 10px !important;
    margin-bottom: 10px !important;
    position: relative;
    &:hover .del {
      display: block;
      height: 15px;
    }
    .del {
      line-height: 15px;
      border-radius: 1px;
      padding: 2px 0;
      text-align: center;
      display: none;
      width: 100%;
      height: 0;
      overflow: hidden;
      position: absolute;
      left: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      color: #fff;
      font-size: 14px;
      transition: linear all 0.5s;
    }
    /deep/ .el-image {
      border-radius: 5px;
      height: 100%;
      width: 100%;
    }
  }
}
.tip {
  padding: 0 10px;
  font-size: 14px;
  color: rgb(176, 176, 176);
}
/deep/ .el-form-item__content {
  line-height: normal;
}

.picList {
  padding: 0 20px;
}
</style>
